<template>
  <div class="profile-container">
    <template v-if="!isAdmin">
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <h2>个人信息设置</h2>
          </div>
        </template>

        <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" class="profile-form">
          <el-form-item :label="userTypeLabel" prop="userId">
            <el-input v-model="userForm.userId" disabled></el-input>
          </el-form-item>

          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name"></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model="userForm.phoneNumber"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>

          <el-form-item v-if="isTeacher" label="教授科目" prop="subject">
            <el-input v-model="userForm.subject"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </template>

    <el-card class="profile-card password-card">
      <template #header>
        <div class="card-header">
          <h2>修改密码</h2>
        </div>
      </template>

      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="120px" class="password-form">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="changePassword">更新密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const userFormRef = ref(null)
const passwordFormRef = ref(null)
const router = useRouter()

// 用户类型判断
const userRole = computed(() => {
  const role = localStorage.getItem('userRole')
  console.log('当前用户角色:', role)
  return role
})

const isTeacher = computed(() => userRole.value === '1')
const isStudent = computed(() => userRole.value === '2')
const isAdmin = computed(() => userRole.value === '3')
const userTypeLabel = computed(() => {
  if (isTeacher.value) return '教师ID'
  if (isStudent.value) return '学生ID'
  if (isAdmin.value) return '管理员ID'
  return '用户ID'
})

// 检查用户角色
const checkUserRole = () => {
  const role = userRole.value
  if (!role) {
    ElMessage.error('未检测到用户角色，请重新登录')
    router.push('/login')
    return false
  }
  return true
}

// 用户表单数据
const userForm = reactive({
  userId: '',
  name: '',
  phoneNumber: '',
  email: '',
  subject: ''
})

// 密码表单数据
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('您尚未登录或登录已过期，请重新登录')
      return
    }

    // 根据用户角色选择不同的API
    let apiUrl = ''
    if (isTeacher.value) {
      apiUrl = '/api/teachers/profile'
    } else if (isStudent.value) {
      apiUrl = '/api/student/profile'
    } else if (isAdmin.value) {
      apiUrl = '/api/admin/profile'
    }

    const response = await axios.get(apiUrl, {
      headers: {
        'Authorization': token
      }
    })

    if (response.data) {
      let userData = response.data
      if (!isTeacher.value && response.data.data) {
        userData = response.data.data
      }

      // 填充表单数据
      if (isTeacher.value) {
        userForm.userId = userData.teacherId || ''
      } else if (isStudent.value) {
        userForm.userId = userData.studentId || ''
      } else if (isAdmin.value) {
        userForm.userId = userData.adminId || ''
      }

      userForm.name = userData.name || ''
      userForm.phoneNumber = userData.phone || ''
      userForm.email = userData.email || ''

      if (isTeacher.value) {
        userForm.subject = userData.subject || ''
      }

      console.log('获取到的用户信息:', userData)
    } else {
      console.error('获取用户信息返回格式异常:', response.data)
      ElMessage.error('获取用户信息失败，返回数据格式异常')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else {
      ElMessage.error('获取用户信息失败，请稍后再试')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 根据用户角色选择不同的API
        let apiUrl = ''
        if (isTeacher.value) {
          apiUrl = '/api/teachers/profile'
        } else if (isStudent.value) {
          apiUrl = '/api/student/profile'
        } else if (isAdmin.value) {
          apiUrl = '/api/admin/profile'
        }

        const requestData = {
          name: userForm.name,
          phoneNumber: userForm.phoneNumber,
          email: userForm.email
        }

        if (isTeacher.value) {
          requestData.subject = userForm.subject
        }

        await axios.put(apiUrl, requestData, {
          headers: {
            'Authorization': localStorage.getItem('token')
          }
        })

        ElMessage.success('个人信息更新成功')
      } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新个人信息失败，请稍后再试')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
    fetchUserInfo()
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }
    
    const userRole = localStorage.getItem('userRole');
    const adminId = localStorage.getItem('userId');
    
    const requestData = {
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword,
      confirmPassword: passwordForm.value.confirmPassword,
      userRole: userRole,
      adminId: adminId
    };
    
    console.log('密码修改请求数据:', requestData);
    
    const response = await axios.put('/api/auth/change-password', requestData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    console.log('密码修改响应:', response.data);
    
    if (response.data.success) {
      ElMessage.success('密码修改成功，请重新登录');
      // 清除用户信息
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('userRole');
      localStorage.removeItem('userName');
      // 重置表单
      passwordFormRef.value.resetFields();
      // 跳转到登录页
      router.push('/login');
    } else {
      ElMessage.error(response.data.message || '密码修改失败');
    }
  } catch (error) {
    console.error('密码修改失败:', error);
    if (error.response) {
      console.error('错误响应:', error.response.data);
      ElMessage.error(error.response.data.message || '密码修改失败');
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接');
    } else {
      ElMessage.error(error.message || '密码修改失败');
    }
  }
};

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  if (!checkUserRole()) return
  if (!isAdmin.value) {
    fetchUserInfo()
  }
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form, .password-form {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
}
</style> 